package cn.bonoon.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.lang.StringUtils;

public class ImageUtil {
	
	/** 把图片按宽度进行等比例压缩 */
	public static void zoom(InputStream input, File targetFile, String filename, int maxWidth) throws Exception{
		BufferedImage bufferedImage = ImageIO.read(input);
		
		int width = Math.min(bufferedImage.getWidth(), maxWidth);
		int height = bufferedImage.getHeight();
		
		if(bufferedImage.getWidth() > width){//进行的压缩
			double scale = (double)bufferedImage.getWidth() / (double)width;    // 缩放的比例
			height =  (int)(height / scale);
		}
		
		if(filename.endsWith(".png") || filename.endsWith(".gif")){
			BufferedImage to= new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); 
			to.createGraphics().drawImage(bufferedImage,0,0, width, height, Color.WHITE, null);
			ImageIO.write(to, "jpg", targetFile);
		}else{
			BufferedImage newImage = new BufferedImage(width, height, bufferedImage.getType());
			Graphics g = newImage.getGraphics();
            g.drawImage(bufferedImage, 0, 0, width, height, null);
            g.dispose();
            //targetFile.createNewFile();
            ImageIO.write(newImage, StringUtils.substringAfterLast(filename, "."), targetFile);
		}
	}
}
